from django.shortcuts import render

# Create your views here.


from pprint import pprint

from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.goods.models import ContentCategory, SKU
from apps.goods.untils import get_categories, get_breadcrumb, get_goods_specs


class IndexView(View):
    """查询首页数据"""
    def get(self, request):

        # 1.获取 商品分类数据
        categories = get_categories()

        # 2.获取广告数据
        contents = {}

        # 1. 获取所有的 广告分类 ContentCategory
        content_categories = ContentCategory.objects.all()

        # 2. 遍历广告分类
        for cat in content_categories:
            # 3. 根据分类 获取 对应 广告内容 Content==1:n
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 8.构建前端数据
        context = {
            'categories': categories,
            'contents': contents
        }
        pprint(contents)
        # 9.返回渲染的模板文件--- 数据 -- 自行渲染
        return render(request, 'index.html', context)


class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        goods_specs = get_goods_specs(sku)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)
